/*
 * Copyright 2008-2012 WebEqua
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.mathcloud.math.io.utility.generic;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.LineNumberReader;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.io.Writer;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class GenericFileUtility
{

	public static String file2String(String fileName)
	{
	  byte[] buffer = new byte[(int) new File(fileName).length()];
	  BufferedInputStream f = null;
	  try
	  {
	    f = new BufferedInputStream(new FileInputStream(fileName));
	    f.read(buffer);
	    f.close();
	    return new String(buffer);
	  } catch (FileNotFoundException e)
	  {
	    log.error("File not found - ", e);
	  } catch (IOException e)
	  {
	  	log.error("Cannot read from file - ",e);
	  }
	  return null;
	}
	
	public static void string2File(String fileName, String output, String encoding)
	{
    Writer out;
		try
		{
			String fencode = (encoding!=null)?encoding:DEFAULT_CHARSET;
			out = new OutputStreamWriter(new FileOutputStream(fileName), fencode);
			out.write(output);
	    out.close();
		} catch (UnsupportedEncodingException e)
		{
			log.error("Incorrect encoding - ", e);
		} catch (FileNotFoundException e)
		{
			log.error("File not found - ", e);
		} catch (IOException e)
		{
			log.error("Cannot write to file - ",e);
		}
	}
	
	public static long countLinesInFile(String filename) throws IOException 
	{
    LineNumberReader reader  = new LineNumberReader(new FileReader(filename));
    long cnt = 0;
    while (reader.readLine() != null) {}
    cnt = reader.getLineNumber(); 
    reader.close();
    return cnt;
	}
	
	public static final String DEFAULT_CHARSET = "UTF-8";
	public static final Logger log = LoggerFactory.getLogger(GenericFileUtility.class);
}
